Page({
  data: {
    // 装修按钮数据
    decorationButtons: [
      { name: "整体装修", value: "full" },
      { name: "贴瓷砖", value: "tile" },
      { name: "老房翻新", value: "old" }
    ],
    // 维修按钮数据
    repairButtons: [
      { name: "疏通下水", value: "pipe" },
      { name: "墙面维修", value: "wall" },
      { name: "水电维修", value: "electric" }
    ],
    activeValue: null,
    decorationBgImage: '/images/183.jpg',
    repairBgImage: '/images/321.jpg',
    phoneNumber: '',
    remark: '',
    selectedDateTime: '',
    multiArray: [[], [], [], []], // 年、月、日、时间
    multiIndex: [0, 0, 0, 0],
    startDate: '',
    endDate: ''
  },

  onLoad: function() {
    // 初始化时间选择器数据
    this.initDateTimePicker();
  },

  // 初始化时间选择器数据
  initDateTimePicker: function() {
    const now = new Date();
    const startYear = now.getFullYear();
    const endYear = startYear + 1;
    
    // 生成年份数组
    const years = [];
    for (let i = startYear; i <= endYear; i++) {
      years.push(i + '年');
    }
    
    // 生成月份数组
    const months = [];
    for (let i = 1; i <= 12; i++) {
      months.push(i + '月');
    }
    
    // 生成日期数组（默认31天，实际选择月份时会更新）
    const days = [];
    for (let i = 1; i <= 31; i++) {
      days.push(i + '日');
    }
    
    // 生成时间数组（9:00-21:00，每30分钟间隔）
    const times = [];
    for (let hour = 9; hour <= 21; hour++) {
      for (let minute = 0; minute < 60; minute += 30) {
        const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
        times.push(timeStr);
      }
    }
    
    this.setData({
      multiArray: [years, months, days, times],
      startDate: `${startYear}-01-01`,
      endDate: `${endYear}-12-31`
    });
  },

  // 多列选择器变化
  bindMultiPickerChange: function(e) {
    const index = e.detail.value;
    const { multiArray } = this.data;
    
    const year = multiArray[0][index[0]].replace('年', '');
    const month = multiArray[1][index[1]].replace('月', '').padStart(2, '0');
    const day = multiArray[2][index[2]].replace('日', '').padStart(2, '0');
    const time = multiArray[3][index[3]];
    
    const selectedDateTime = `${year}-${month}-${day} ${time}`;
    
    this.setData({
      multiIndex: index,
      selectedDateTime: selectedDateTime
    });
  },

  // 列变化时更新数据
  bindMultiPickerColumnChange: function(e) {
    const column = e.detail.column;
    const value = e.detail.value;
    
    if (column === 0 || column === 1) {
      // 年或月变化时，更新日期列
      this.updateDaysColumn(value, column);
    }
  },

  // 更新日期列
  updateDaysColumn: function(value, column) {
    const { multiArray, multiIndex } = this.data;
    let yearIndex = multiIndex[0];
    let monthIndex = multiIndex[1];
    
    if (column === 0) {
      yearIndex = value;
    } else if (column === 1) {
      monthIndex = value;
    }
    
    const year = parseInt(multiArray[0][yearIndex].replace('年', ''));
    const month = parseInt(multiArray[1][monthIndex].replace('月', ''));
    
    // 计算该月的天数
    const daysInMonth = new Date(year, month, 0).getDate();
    
    // 更新日期数组
    const days = [];
    for (let i = 1; i <= daysInMonth; i++) {
      days.push(i + '日');
    }
    
    // 更新multiArray
    const newMultiArray = [...this.data.multiArray];
    newMultiArray[2] = days;
    
    // 如果当前选择的日期大于该月天数，则重置为最后一天
    let dayIndex = multiIndex[2];
    if (dayIndex >= daysInMonth) {
      dayIndex = daysInMonth - 1;
    }
    
    const newMultiIndex = [...this.data.multiIndex];
    newMultiIndex[2] = dayIndex;
    
    this.setData({
      multiArray: newMultiArray,
      multiIndex: newMultiIndex
    });
  },

  // 处理备注输入
  onRemarkInput: function(e) {
    this.setData({
      remark: e.detail.value
    });
  },

  // 处理电话输入
  onPhoneInput: function(e) {
    this.setData({
      phoneNumber: e.detail.value
    });
  },

  // 选择服务
  handleSelect: function(e) {
    this.setData({
      activeValue: e.currentTarget.dataset.value
    });
  },

  // 提交表单
  handleSubmit: function() {
    // 表单验证
    if (!this.data.activeValue) {
      wx.showToast({ 
        title: '请选择一项服务', 
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (!this.data.selectedDateTime) {
      wx.showToast({ 
        title: '请选择预约时间', 
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (!this.data.phoneNumber) {
      wx.showToast({ 
        title: '请输入手机号码', 
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(this.data.phoneNumber)) {
      wx.showToast({ 
        title: '请输入正确的手机号码', 
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 提交数据
    const formData = {
      service: this.data.activeValue,
      datetime: this.data.selectedDateTime,
      phone: this.data.phoneNumber,
      remark: this.data.remark
    };
    
    console.log('提交的表单数据:', formData);
    
    // 显示成功提示
    wx.showToast({
      title: '预约成功！',
      icon: 'success',
      duration: 2000,
      success: () => {
        // 2秒后重置表单
        setTimeout(() => {
          this.setData({
            activeValue: null,
            selectedDateTime: '',
            phoneNumber: '',
            remark: '',
            multiIndex: [0, 0, 0, 0]
          });
          this.initDateTimePicker();
        }, 2000);
      }
    });
  }
});